<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>{{ $route.query.id ? '试题修改' : '试题录入' }}</span>
    </div>
    <!-- 表单区域 -->
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
      <!-- 下拉框区  
      双向绑定的是option中的value值 :key绑定的值是number或string-->
      <el-form-item label="学科：" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择" class="select" @change="getCatalog">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in subjects"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录：" prop="catalogID">
        <el-select
          v-model="form.catalogID"
          placeholder="请选择"
          class="select"
          @change="getQuestionTag"
        >
          <el-option
            :label="item.directoryName"
            :value="item.id"
            v-for="(item, index) in catalog"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业：" prop="enterpriseID">
        <el-select v-model="form.enterpriseID" placeholder="请选择" class="select">
          <el-option
            :label="item.company"
            :value="item.id"
            v-for="item in enterprises"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 省会和城市 连个组件间有从属关系 -->
      <el-form-item label="城市：" prop="province">
        <!-- 双下拉框 -->
        <el-select class="doubble" v-model="form.province" placeholder="请选择" @change="getCitys">
          <el-option v-for="(item,index) in provinces" :key="index" :label="item" :value="item"></el-option>
        </el-select>

        <el-select
          class="doubble"
          v-model="form.city"
          collapse-tags
          style="margin-left: 10px;"
          placeholder="请选择"
        >
          <el-option v-for="(item,index) in citys" :key="index" :label="item" :value="item"></el-option>
        </el-select>
        <!-- 双下拉框 -->
      </el-form-item>

      <!-- 方向 -->
      <el-form-item label="方向：" prop="direction">
        <el-select v-model="form.direction" placeholder="请选择" class="select">
          <el-option :label="item" :value="item" v-for="(item, index) in direction" :key="index"></el-option>
        </el-select>
      </el-form-item>

      <!-- 下拉框区 单选按钮是change事件-->

      <!-- 题型 单选框 -->
      <el-form-item label="题型：" prop="questionType">
        <el-radio-group v-model="form.questionType">
          <el-radio :label=" '1' ">单选</el-radio>
          <el-radio :label=" '2' ">多选</el-radio>
          <el-radio :label=" '3' ">简答</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 难度 单选框-->
      <el-form-item label="难度：" prop="difficulty">
        <el-radio-group v-model="form.difficulty">
          <el-radio :label=" '1' ">简单</el-radio>
          <el-radio :label=" '2' ">一般</el-radio>
          <el-radio :label=" '3' ">困难</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 富文本编辑器  题干 -->
      <el-form-item label="题干：" prop="question">
        <quill-editor v-model="form.question" :options="editorOption"></quill-editor>
      </el-form-item>
      <!-- 
      checkbox-group元素能把多个 checkbox 管理为一组，
      只需要在 Group 中使用v-model绑定Array类型的变量即可。 
      el-checkbox 的 label属性是该 checkbox 对应的值，
      若该标签中无内容，则该属性也充当 checkbox 按钮后的介绍。
      label与数组中的元素值相对应，如果存在指定的值则为选中状态，否则为不选中。
      单选框v-model要绑定相同的值得到单选功能,
      单个复选框 绑定布尔值, 多个复选框绑定一个数组
      -->
      <!-- 选项区  需要分情况和试题类型进行关联-->
      <!-- 通过试题类型 单选/多选 绑定的值进行确定显示 单选/复选框 -->
      <el-form-item label="选项：" prop="options" v-show="form.questionType !=='3'">
        <el-row v-for="(item, index) in form.options" :key="index">
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">

              <el-checkbox
                v-model="item.isRight"
                :label="1"
                v-if="form.questionType === '2'"
                style="margin-right:0"
              >{{item.code}} ：</el-checkbox>

              <el-radio
                v-model="item.isRight"
                :label="1"
                v-if="form.questionType === '1'"
                style="margin-right:0"
                @change="singleSelect(index)"
              >{{item.code}} ：</el-radio>

              <el-input v-model="item.title" style="width:26%"></el-input>
              <!-- action必选 上传的地址 -->
              <el-upload
                class="avatar-uploader upload-demo"
                :action="item.img"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <i class="el-icon-circle-close avatar-uploader-icon icon"></i>
              </el-upload>
            </div>
          </el-col>
        </el-row>

        <!-- 增加选项按钮 -->
        <el-button
          type="danger"
          style="margin-top: 10px"
          ref="addBtn"
          :disabled="form.questionType !== '2'"
          @click="addOption"
        >+增加选项与答案</el-button>
      </el-form-item>

      <!-- 视频解析 -->
      <el-form-item label="解析视频：" prop="videoURL">
        <el-input v-model="form.videoURL" style="width:40%"></el-input>
      </el-form-item>

      <!-- 富文本编辑器 答案解析-->
      <el-form-item label="答案解析：" prop="answer">
        <quill-editor v-model="form.answer" :options="editorOption"></quill-editor>
      </el-form-item>

      <!-- 题目备注 -->
      <el-form-item label="题目备注：" prop="remarks">
        <el-input type="textarea" v-model="form.remarks" rows="5" style="width:40%"></el-input>
      </el-form-item>

      <!-- 试题标签  里边有连个值 label 'h5'和 value 12-->
      <el-form-item label="试题标签：" prop="tags">
        <el-select v-model="form.tags" placeholder="请选择试题标签" class="tag" multiple>
          <el-option
            v-for="(item, index) in questionTag"
            :value="item.value"
            :label="item.label"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 确认按钮 通过地址栏传过来的query.id的有无, 来确定修改还是提交-->
      <el-form-item>
        <el-button type="success" @click="submitForm('form')" v-if="$route.query.id">确认修改</el-button>
        <el-button v-else type="primary" @click="submitForm('form')">确认提交</el-button>
      </el-form-item>
    </el-form>
    <!-- 表单区域 -->
  </el-card>
</template>

<script>
//引入富文本编辑器 ,以及样式
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
//引入接口
import { simple } from "@/api/hmmm/subjects";
import { list as catalogList } from "@/api/hmmm/directorys";
import { list } from "@/api/hmmm/companys";
import { citys, provinces } from "@/api/hmmm/citys";
import { simple as tagList } from "@/api/hmmm/tags";
import { add, update, detail } from "@/api/hmmm/questions";
//用于列表按钮渲染的数据
import { direction, questionType, difficulty } from "@/api/hmmm/constants";

export default {
  data() {
    return {
      //表单绑定的数据
      form: {
        subjectID: "", //学科
        catalogID: "", //目录
        enterpriseID: "", //企业
        questionType: "1", //题型 string
        difficulty: "1", //难度 string
        city: "", //地方市级
        province: "", //省会
        direction: "", //方向
        question: "", //题干
        videoURL: "", //视频解析
        answer: "", //答案解析
        remarks: "", //题目备注
        tags: "", //试题标签
        options: [
          //选项 array
          { code: "A", title: "", img: "", isRight: 0 },
          { code: "B", title: "", img: "", isRight: 0 },
          { code: "C", title: "", img: "", isRight: 0 },
          { code: "D", title: "", img: "", isRight: 0 },
        ],
      },
      //用于渲染的数据

      subjects: [], //学科
      catalog: [], //目录
      enterprises: [], //企业
      provinces: [], //省会
      questionType: null, //题型
      difficulty: null, //难度
      citys: [], //地方城市
      direction: direction, //方向
      questionTag: [],

      //富文本编辑器的配置项
      editorOption: {
        placeholder: "", //占位文字
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            [{ list: "ordered" }, { list: "bullet" }],
            ["blockquote"],
            ["code-block", "image", "link"],
          ],
        },
      },
      //表单验证规则
      rules: {
        subjectID: [
          { required: true, message: "学科不能为空", trigger: "change" },
        ],
        catalogID: [
          { required: true, message: "目录不能为空", trigger: "change" },
        ],
        enterpriseID: [
          { required: true, message: "企业不能为空", trigger: "change" },
        ],
        province: [
          { required: true, message: "省会不能为空", trigger: "change" },
        ],
        direction: [
          { required: true, message: "方向不能为空", trigger: "change" },
        ],
        questionType: [
          { required: true, message: "题型不能为空", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "难度不能为空", trigger: "change" },
        ],
        question: [
          { required: true, message: "题干不能为空", trigger: "change" },
        ],
        answer: [
          { required: true, message: "答案解析不能为空", trigger: "change" },
        ],
      },
    };
  },
  components: {
    //引入富文本编辑器
    quillEditor,
  },
  methods: {
    //两个文件事件处理程序:
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //实现单选框单选的问题: 排他事件
    singleSelect(idx) {
      this.form.options.forEach((item, index) => {
        item.isRight = 0;
        if (index === idx) {
          item.isRight = 1;
        }
      });
    },

    //获取表单初始化数据
    async getDatas() {
      //获取学科
      const res1 = await simple();
      this.subjects = res1.data;
      // console.log( res1.data);
      //获取公司列表
      const res2 = await list();
      this.enterprises = res2.data.items;
      // console.log(res2.data.items);
      //获取省会列表
      const res3 = await provinces();
      // console.log(res3);
      this.provinces = res3;
    },

    //获取地方城市数据列表
    async getCitys() {
      //根据省会获取地方城市列表
      const res4 = await citys(this.form.province);
      // console.log(res4);
      this.citys = res4;
    },

    //目录根据学科id获取
    async getCatalog() {
      //获取学科目录列表
      const res6 = await catalogList({
        subjectID: this.form.subjectID,
      });
      // console.log(res6);
      this.catalog = res6.data.items;
    },

    //获取试题标签列表
    async getQuestionTag() {
      const res7 = await tagList({
        subjectID: this.form.subjectID,
      });
      console.log(res7.data);
      this.questionTag = res7.data;
    },

    //点击提交按钮,发起请求
    submitForm(form) {
      //1. 进行整体校验
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          //校验成功进行提交，录入成功后，提示“修改成功”+跳转到基础题库列表
          //全部通过,则发送请求,进行页面跳转
          //参数非必须 , 标签参数有数组变成字符串,满足接口请求
          //这里需要是 试题录入 还是 修改试题 的判断
          if(!this.$route.query.id){
            try{
                this.form.tags = this.form.tags.join();
                const res = await add(this.form);
                // console.log(res);
                // 提示+跳转
                this.$message.success("录入成功");
            }catch{
                this.$message.warning("录入失败");
                return false;
            }
          }else{
            try{
              const res = await update(this.form);
              console.log(res);    
              this.$message.success("修改成功"); 
            }catch{
              this.$message.warning("修改失败");
              return false;
            }
          }
            this.$router.push({
              path: "/questions/list",
            });
            //表单清空
            this.$refs[form].resetFields();
        } else {
          //否则提示
          this.$message.warning("有没填写的哦!!");
          return false;
        }
      });
    },

    //数据回填
    async reBackQuestion() {
      const id = this.$route.query.id;
      //判断是不是从基础题库过来的, 
      if(id){
        const res = await detail({id});
        this.form = res.data;
        this.form
      }
      // console.log(res);      
    },
    
    //增加选项和答案
    addOption() {
      //实现视图都是操作数据,添加减少就是给数组push/splice元素
      //String.fromCharCode(n1, n2, ..., nX)
      //String.fromCharCode(72,69,76,76,79); //HELLO
      this.form.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.form.options.length),
        title: "",
        img: "",
      });
    },
  },
  //表单初始化获取数据的调用:
  mounted() {
    this.getDatas();
    this.reBackQuestion();
  },
};
</script>

<style scoped lang='less'>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  margin: 15px;
}
.select {
  width: 40%;
}
.doubble {
  width: 19.5%;
}
.tag {
  width: 40%;
}
.avatar-uploader {
  position: relative;
  display: inline-block;
  width: 80px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin-left: 10px;
  /deep/.el-upload {
    border-radius: 6px;
    width: 78px;
    height: 48px;
    cursor: pointer;
    overflow: hidden;
    .icon {
      position: absolute;
      top: -24px;
      right: -9px;
      font-size: 18px;
      z-index: 2;
    }
  }
  /deep/.el-icon-plus::before {
    position: relative;
    left: -4px;
  }
}
.grid-content {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 18px;
  height: 18px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 50px;
  display: inline-block;
}
/deep/.ql-editor {
  height: 100px;
}
</style>
